package dead.queue.at.demo.config;


import dead.queue.at.demo.entity.MessageNameConfig;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DirectRabbitConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory)
    {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        //设置Json转换器
        rabbitTemplate.setMessageConverter(jsonMessageConverter());

        return rabbitTemplate;
    }

    /**
     * Json转换器
     */
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }



    @Bean
    public Queue dlxQueue() {
        return new Queue(MessageNameConfig.testDeadLetterQueueName);
    }

    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(MessageNameConfig.testDeadLetterExchangeName);
    }


    @Bean
    public Binding binding() {
        return BindingBuilder.bind(dlxQueue())
                .to(dlxExchange())
                .with(MessageNameConfig.testDeadLetterRoutingKey);
    }

    @Bean
    public Queue TestDirectQueue() {
        Map<String,Object> arguments = new HashMap<>();
        // 绑定死信到队列
        arguments.put("x-dead-letter-exchange", MessageNameConfig.testDeadLetterExchangeName);
        arguments.put("x-dead-letter-routing-key", MessageNameConfig.testDeadLetterRoutingKey);
        return new Queue(MessageNameConfig.testQueueName,true,false, false, arguments);
    }

    //Direct交换机 起名：TestDirectExchange
    @Bean
    DirectExchange TestDirectExchange() {
        return new DirectExchange(MessageNameConfig.testExchangeName,true,false);
    }

    //绑定  将队列和交换机绑定, 并设置用于匹配键：TestDirectRouting
    @Bean
    Binding bindingDirect() {
        return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with(MessageNameConfig.testRoutingKey);
    }
}
